<template>
  <div class="Wrapper ">
    <div class="content ">
      <div class="mapBox" :style="{ backgroundImage: `url(${site_config.front_background})` }">
        <div class="list" v-for="(item, index) in site_location" :key="index" :style="{
          width: item.width + 'px',
          height: item.height + 'px',
          left: item.x + 'px',
          top: item.y + 'px',
        }" @click="selectTab(item)">
          <img :src="item.choose_log" class="list_img emptyImg" v-if="item.select == 1" :alt="item.name" />
          <div v-else>
            <img :src="item.empty_log" class="list_img emptyImg"
              v-if="item.order_state == 0 || item.order_state == 2" />
            <img :src="item.order_log" class="list_img" v-if="item.order_state == 1" />
          </div>
        </div>
        <img :src="site_config.background" alt="" class="mapImg" />
      </div>
    </div>

    <div class="Select_location ">
      <div class="getVid">
        <span class="getVid_text">手机号：</span>
        <el-input v-model="phone" type="text" placeholder="请输入手机号码" maxlength="11" class="getVid_input"
          @input="handlePhoneInput" />
      </div>
      <!-- 查詢用户 -->
      <div class="UserInfo" v-if="User">
        <img :src="imgUrls(User.v_headimg)" alt="" class="v_headimg">
        <div class="Info">
          <p class="v_name">vid：{{ User.v_id }}</p>
          <p class="v_name">昵称：{{ User.v_name }}</p>
          <p class="v_name">电话：{{ User.v_tel }}</p>
        </div>
      </div>

      <!-- 选择的座位 -->
      <div class="selectSeat">
        <div class="list" v-for="(item) in selectArr" :key="item.id">
          <span class="list_name">{{ item.name }}</span>
          <el-input v-model="item.order_price" type="text" placeholder="自定义预约费" class="list_input" />
          <el-input v-model="item.site_price" type="text" placeholder="自定义原价" class="list_input" />


        </div>
        <el-empty description="暂未选座" v-if="selectArr.length == 0" />
      </div>

      <div class="Continue " :class="{ 'Active': Pass }" @click="Continue">确定</div>

    </div>
  </div>
</template>
<script setup>
import Http from '@/utils/http';
import { imgUrls } from '@/utils/utils';
import { useRoute } from 'vue-router';
import { useMainStore } from '@/stores/useMain';

const mainStore = useMainStore();
const route = useRoute();
const site_config = ref('');
const site_location = ref([]); // 座位
const id = ref(route.query.id || 587);
const selectArr = ref([]);
const phone = ref('');
const User = ref('');
const loading = ref(false);
const Pass = ref(false);
onMounted(() => {
  document.title = '创建订单';
  getSiteTimeDetail();
});

const selectTab = (item) => {
  if (item.order_state == 1) return this.$Toast('该座位已被预约，请重新选择');
  if (item.order_state == 2) return;
  // if (item.tel == 1) return (this.show = true);
  const Flag = containsObjectWithData(selectArr.value, 'id', item.id);
  const Index = site_location.value.findIndex((n) => n.id == item.id);
  if (Flag) {
    const selectIndex = selectArr.value.findIndex((n) => n.id == item.id);
    selectArr.value.splice(selectIndex, 1);
    site_location.value[Index].select = 0;
  } else {
    selectArr.value.push(item);
    site_location.value[Index].select = 1;
  }


};

const containsObjectWithData = (objects, key, value) => {
  return objects.some((obj) => obj[key] === value);
};

const getSiteTimeDetail = () => {
  Http.get({
    url: '/SiteApi/getSiteTimeDetail',
    params: {
      id: id.value
    },
  }).then((res) => {
    if (res.code != 200) return ElMessage(res.msg);
    const Result = res.data;
    site_config.value = Result.site_config;

    Result.site_location.forEach((item) => {
      item.width = Math.round(Number(Result.site_config.width));
      item.height = Math.round(Number(Result.site_config.height));
      item.x = Math.round(Number(item.x));
      item.y = Math.round(Number(item.y));
      item.site_price = '';
      item.order_price = '';
      let userItem = Result.type_config.find((n) => n.id == item.site_type);
      if (userItem) {
        item.empty_log = userItem.empty_log;
        item.choose_log = userItem.choose_log;
        item.order_log = userItem.order_log;
        item.type_name = userItem.type_name;
      }
    });
    site_location.value = Result.site_location;
  });
};

const Continue = () => {
  // 检查是否有用户信息
  if (!User.value) {
    ElMessage.warning('请先输入手机号查询用户信息');
    return;
  }

  // 检查是否选择了座位
  if (selectArr.value.length === 0) {
    ElMessage.warning('请至少选择一个座位');
    return;
  }

  // 先检查是否有空值
  const hasEmptyValue = selectArr.value.some(item => {
    if (!item.site_price) {
      ElMessage.warning(`座位 ${item.name} 的预约费不能为空`);
      return true;
    }
    if (!item.order_price) {
      ElMessage.warning(`座位 ${item.name} 的原价不能为空`);
      return true;
    }
    return false;
  });

  if (hasEmptyValue) return;

  // 再检查是否都是数字
  const isValidNumber = selectArr.value.every(item => {
    if (isNaN(Number(item.site_price))) {
      ElMessage.warning(`座位 ${item.name} 的预约费必须为数字`);
      return false;
    }
    if (isNaN(Number(item.order_price))) {
      ElMessage.warning(`座位 ${item.name} 的原价必须为数字`);
      return false;
    }
    return true;
  });

  if (!isValidNumber) return;

  Pass.value = true;

  // 构建FormData
  const formData = new FormData();
  formData.append('postArr[id]', id.value);
  formData.append('postArr[v_id]', User.value.v_id);
  formData.append('type', 'doCreateOrder');


  // 添加table数组和价格数据
  selectArr.value.forEach((item, index) => {
    formData.append(`postArr[table][${index}]`, item.id);
    formData.append(`postArr[site_price][${item.id}]`, item.site_price);
    formData.append(`postArr[order_price][${item.id}]`, item.order_price);
  });

  // 发送请求
  Http.post({
    url: '/Site/siteEdit',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(res => {
    if (res.code == 100) {
      ElMessage({
        message: '操作成功',
        type: 'success',
      })

      // 重新获取座位数据
      getSiteTimeDetail();
      // 清空选择
      selectArr.value = [];
      Pass.value = false;
    } else {
      ElMessage.error(res.msg || '操作失败');
    }
  }).catch(() => {
    ElMessage.error('操作失败');
  });
}

// 手机号验证函数
const validatePhone = (phone) => {
  const reg = /^1[3-9]\d{9}$/;
  return reg.test(phone);
};

// 查询处理函数
const handleSearch = async () => {
  if (!phone.value) {
    return ElMessage.warning('请输入手机号码');
  }
  if (!validatePhone(phone.value)) {
    return ElMessage.warning('请输入正确的手机号码');
  }

  loading.value = true;
  try {
    const res = await Http.get({
      url: '/Site/getPhoneToVid',
      params: {
        phone: phone.value
      }
    });

    if (res.code != 100) return ElMessage.error(res.msg || '查询失败');
    const result = res.data;
    User.value = result
  } catch (error) {
    ElMessage.error('查询失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 监听手机号输入
const handlePhoneInput = (value) => {
  // 当输入长度达到11位且是有效手机号时自动查询
  if (value.length === 11 && validatePhone(value)) {
    handleSearch();
  }
};
</script>
<style lang="scss" scoped>
.Wrapper {
  width: 100%;
  min-height: 100vh;
  padding: 20px 50px;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
  background-color: #f2f2f2;

  .content {
    width: 100%;

    height: calc(100vh - 40px);
    box-sizing: border-box;

    .mapBox {
      width: 750px;
      height: 100%;
      background-size: cover;
      background-position: center;
      overflow-y: auto;
      -webkit-user-select: none;
      user-select: none;
      box-sizing: border-box;
      scrollbar-width: none;
      -ms-overflow-style: none;

      position: relative;

      &::-webkit-scrollbar {
        display: none;
      }

      .list {
        position: absolute;
        z-index: 100;

        .list_img {
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
        }

        .emptyImg {
          cursor: pointer;
        }
      }

      .mapImg {
        width: 100%;
        height: auto;
        display: block;
        max-width: 100%;
      }
    }
  }

  .Select_location {
    width: 700px;
    height: 100%;
    padding: 20px;
    height: calc(100vh - 40px);
    display: flex;
    flex-direction: column;
    background-color: #ffffff;
    border-radius: 10px;

    .lookUser {
      color: #000;
      font-size: 18px;
    }

    .getVid {
      width: 100%;
      display: flex;
      align-items: center;

      .getVid_text {
        font-size: 17px;
        color: #999;
      }

      .getVid_input {
        flex: 1;
        height: 44px;
        margin-left: 20px;
        font-size: 16px;
      }

      .search-btn {
        margin-left: 10px;
        height: 50px;
        padding: 0 20px;
      }
    }

    .UserInfo {
      display: flex;
      align-items: center;
      margin-top: 30px;

      .v_headimg {
        width: 70px;
        height: 70px;
        border-radius: 4px;
        margin-right: 20px;
      }

      .Info {
        height: 70px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .v_name {
          color: #000;
          font-size: 14px;
        }
      }
    }

    .selectSeat {
      width: 100%;
      flex: 1;
      overflow-y: auto;
      -webkit-user-select: none;
      user-select: none;
      box-sizing: border-box;
      scrollbar-width: none;
      -ms-overflow-style: none;
      margin-top: 30px;

      &::-webkit-scrollbar {
        display: none;
      }

      .list {
        width: 100%;
        display: flex;
        align-items: center;
        margin-bottom: 20px;

        .list_name {
          min-width: 70px;
          color: #333;
          font-size: 16px;
        }

        .list_input {
          flex: 1;
          height: 40px;
          font-size: 16px;
          margin-left: 20px;
        }
      }
    }

    .Continue {
      width: 300px;
      height: 60px;
      background-color: #f2f2f2;
      color: #999;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 20px;
      border-radius: 4px;
      margin: 20px auto 0;
      cursor: pointer;
      position: relative;
      z-index: 1;
      letter-spacing: 10px;
      user-select: none;
    }

    .Active {
      background-color: #66b1ff;
      color: #fff;
    }
  }


}
</style>
